"""
聚类：没有标签的数据分类
K-Means:https://www.bilibili.com/video/av54650064/?spm_id_from=trigger_reload
DBSCAN:https://www.bilibili.com/video/av54693046?from=search&seid=5054833342021355086
评估标准: "簇内差异小，簇外差异大"
轮廓系数：a是样本与同簇点平均距离，b是样本另一个簇最近距离，轮廓系数e=(b-a)/max(a,b),e越
靠近1，说明点与同簇点更相似，e越靠近-1，说明点与其他簇的点更相似，e=0时说明两个簇应该是一个
"""

from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import silhouette_score


"""
K-Meams
"""
# x, y = make_blobs(n_samples=500, n_features=2, centers=4, random_state=22)
# fig, ax = plt.subplots(1, 3, figsize=(12, 4))
# ax[0].scatter(x[:, 0], x[:, 1], s=8)
#
# color = ["r", "green", "b", "orange"]
#
# for i in range(4):
#     ax[1].scatter(x[y == i, 0], x[y == i, 1], s=8, c=color[i])
#
# pred = KMeans(n_clusters=4, random_state=22).fit_predict(x)
# for i in range(4):
#     ax[2].scatter(x[:, 0], x[:, 1], s=8, c=pred)
#
# plt.show()
# print(silhouette_score(x, y))
# print(silhouette_score(x, pred))

"""
DBSCAN：各种数据上表现都非常好
"""
from sklearn.datasets import make_circles, make_blobs
import numpy as np

x1, _ = make_circles(n_samples=5000, factor=.5, noise=0.05)
x2, _ = make_blobs(n_samples=1000, n_features=2, centers=[[1.2,1.2]], cluster_std=0.1)

fig, ax =plt.subplots(1, 3, figsize=(16, 4))
x = np.concatenate((x1, x2))
ax[0].scatter(x[:, 0], x[:, 1], s=8)

from sklearn.cluster import KMeans
pred = KMeans(n_clusters=3).fit_predict(x)
ax[1].scatter(x[:, 0], x[:, 1], s=8, c=pred)  # 不用写y==pred 会自动分

from sklearn.cluster import DBSCAN
pred = DBSCAN(eps=0.1, min_samples=10).fit_predict(x)#提高成簇条件:减小邻域,增大样本数要求
ax[2].scatter(x[:, 0], x[:, 1], s=8, c=pred)

plt.show()